<template>
	<div>
		<basic-container style="display: flex; flex-wrap:wrap;">
			<div :style="DEBUG?'width: 70%;float: left;':'width: 100%;float: left;'">
				<el-row :gutter="28" type="flex">
					<el-col :span="14">
						<el-tag effect="dark">DI {{$t('wel.table.configure')}}</el-tag>
						<avue-crud :data="DIData" :option="DIOption" v-model="DIForm" @row-update="DIUpdate">
						</avue-crud>
					</el-col>
					<el-col :span="12">
						<el-tag effect="dark">DO {{$t('wel.table.configure')}}</el-tag>
						<avue-crud :data="DOData" :option="DOOption" v-model="DOForm" @row-update="DOUpdate">
						</avue-crud>
					</el-col>
				</el-row>

				<el-row :gutter="28" type="flex">
					<el-col :span="14">
						<el-tag effect="dark">AI {{$t('wel.table.configure')}}</el-tag>
						<avue-crud :data="AIData" :option="AIOption" v-model="AIForm" @row-update="AIUpdate">
						</avue-crud>
					</el-col>
					<el-col :span="12">
						<el-tag effect="dark">PWM {{$t('wel.table.configure')}}</el-tag>
						<avue-crud :data="PWMData" :option="PWMOption" v-model="PWMForm" @row-update="PWMUpdate">
						</avue-crud>
					</el-col>
				</el-row>

				<el-row :gutter="28" type="flex">
					<el-col :span="14">
						<el-tag effect="dark">UART {{$t('wel.table.configure')}}</el-tag>
						<avue-crud :data="UARTData" :option="UARTOption" v-model="UARTForm" @row-update="UARTUpdate">
						</avue-crud>
					</el-col>
				</el-row>
			</div>
			<div :style="DEBUG?'width:25%;float:left;margin-left:2rem':'width:0%;float:left;margin-left:2rem'"
				v-if="DEBUG">
				<textarea
					style="background-color: #000000;border-radius: 0.625rem;padding: 0.625rem;color: #FFFFFF;margin-left:2rem;"
					disabled cols="60" rows="30" v-model="logText"></textarea>
				<el-input v-model="sendTheme" style="margin-left:2rem;margin-top: 1.25rem;" disabled />
				<textarea
					style="background-color: #FFFFFF;border-radius: 0.625rem;padding: 0.625rem;color: #000000;margin-left:2rem;margin-top: 1.25rem;"
					cols="60" rows="10" v-model="sendTextMessage"></textarea>
				<el-button type="primary" @click="sendText()" style="margin-left: 1.875rem;margin-top: 1.25rem;">
					{{$t('wel.table.send_out')}}
				</el-button>
			</div>
		</basic-container>
	</div>


</template>

<script>
	import mqtt from 'mqtt'
	import {
		mapGetters
	} from "vuex";
	import request from '@/router/axios';
	import {
		DEBUG,
		baseUrl,
		MQTT_SERVICE,
		MQTT_USERNAME,
		MQTT_PASSWORD
	} from '@/config/env';


	var client;
	var clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)

	const options = {
		connectTimeout: 40000,
		clientId: "user" + clientId,
		username: MQTT_USERNAME,
		password: MQTT_PASSWORD,
		clean: true
	}
	export default {
		name: "wel",

		data() {
			return {
				sendTextMessage: "",
				sendTheme: "",
				logText: "",
				id: 0,
				loading: null,
				isLoadding: false,
				clientStatus: false,
				DIData: [],
				device: {},
				DIOption: {
					labelWidth: 150,
					header: false,
					delBtn: false,
					addBtn: false,
					refreshBtn: false,
					columnBtn: false,
					menuType: "icon",
					column: [{
							'label': this.$t("wel.table.name"),
							prop: "name"
						},
						{
							'label': this.$t("wel.table.code"),
							prop: "num",
							editDisplay: false,
						},
						{
							'label': this.$t("wel.table.ActiveReporting"),
							prop: "isPost",
							type: 'tree',
							dicData: [{
								label: this.$t("wel.table.Close"),
								value: "0"
							}, {
								label: this.$t("wel.table.Open"),
								value: "1"
							}, ],
						},
					]

				},
				DIForm: {},
				UARTForm: {},
				UARTData: [],
				UARTOption: {
					labelWidth: 150,
					header: false,
					delBtn: false,
					addBtn: false,
					refreshBtn: false,
					columnBtn: false,
					menuType: "icon",
					column: [{
							'label': this.$t("wel.table.name"),
							prop: "name"
						},
						{
							'label': this.$t("wel.table.code"),
							prop: "num",
							editDisplay: false,
						},
						{
							'label': this.$t("wel.table.baud"),
							prop: "baud",
							type: 'tree',
							dicData: [{
									label: 1200,
									value: "1200"
								}, {
									label: 2400,
									value: "2400"
								},
								{
									label: 4800,
									value: "4800"
								},
								{
									label: 9600,
									value: "9600"
								},
								{
									label: 19200,
									value: "19200"
								},
								{
									label: 38400,
									value: "38400"
								},
								{
									label: 57600,
									value: "57600"
								},
								{
									label: 115200,
									value: "115200"
								},
								{
									label: 230400,
									value: "230400"
								},
								{
									label: 460800,
									value: "460800"
								},
							],
						},
						{
							'label': this.$t("wel.table.parity"),
							prop: "parity",
							type: 'tree',
							dicData: [{
									label: "NONE",
									value: "NONE"
								}, {
									label: "ODD",
									value: "ODD"
								},
								{
									label: "EVEN",
									value: "EVEN"
								},
							],
						},
						{
							'label': this.$t("wel.table.stop"),
							prop: "stop",
							type: 'tree',
							dicData: [{
								label: "1",
								value: "1"
							}, {
								label: "2",
								value: "2"
							}, ],
						},
						{
							'label': this.$t("wel.table.dataBits"),
							prop: "dataBits",
							type: 'tree',
							dicData: [{
								label: "8",
								value: "8"
							}, {
								label: "7",
								value: "7"
							}, ],
						},
					]
				},
				AIForm: {},
				AIData: [],
				AIOption: {

					labelWidth: 150,
					header: false,
					delBtn: false,
					addBtn: false,
					refreshBtn: false,
					columnBtn: false,
					menuType: "icon",
					column: [{
							'label': this.$t("wel.table.name"),
							prop: "name"
						},
						{
							'label': this.$t("wel.table.code"),
							prop: "num",
							editDisplay: false,
						},
						{
							'label': this.$t("wel.table.ActiveReporting"),
							prop: "isPost",
							type: 'tree',
							dicData: [{
								label: this.$t("wel.table.Close"),
								value: "0"
							}, {
								label: this.$t("wel.table.Open"),
								value: "1"
							}, ],
						},
					]

				},
				DOForm: {},
				DOData: [],
				DOOption: {
					header: false,
					delBtn: false,
					addBtn: false,
					refreshBtn: false,
					labelWidth: 150,
					columnBtn: false,
					menuType: "icon",
					column: [{
							label: this.$t("wel.table.name"),
							prop: "name"
						},
						{
							label: this.$t("wel.table.code"),
							prop: "num",
							editDisplay: false,
						},
						{
							label: this.$t("wel.table.Working_mode"),
							prop: "mode",
							type: 'tree',
							dicData: [{
								label: "普通输出",
								value: "0"
							}, {
								label: "脉冲输出",
								value: "1"
							}, {
								label: "作为数据灯，收发数据闪烁",
								value: "2"
							}, {
								label: "作为系统状态指示灯",
								value: "3"
							}],
						},
						{
							'label': this.$t("wel.table.ActiveReporting"),
							prop: "isPost",
							type: 'tree',
							dicData: [{
								label: this.$t("wel.table.Close"),
								value: "0"
							}, {
								label: this.$t("wel.table.Open"),
								value: "1"
							}, ],
						},
						{
							label: this.$t("wel.table.pulseTime"),
							prop: "pulseTime",
						},

					]

				},
				PWMForm: {},
				PWMData: [],
				userInfo: {},
				PWMOption: {
					labelWidth: 150,
					header: false,
					delBtn: false,
					addBtn: false,
					refreshBtn: false,
					columnBtn: false,
					menuType: "icon",
					column: [{
							'label': this.$t("wel.table.name"),
							prop: "name"
						},
						{
							'label': this.$t("wel.table.code"),
							prop: "num",
							editDisplay: false,

						},
						{
							'label': this.$t("wel.table.Highleveltimes"),
							prop: "highLevelCnt",
						},
						{
							'label': this.$t("wel.table.divisionFactor"),
							prop: "frqDiv",
						},
						{
							'label': this.$t("wel.table.Totaltimes"),
							prop: "totalCnt",
						},
					]
				},
				dic: [],
				searchText: "",
				data: [],
				type: '',
				box: false,
				formList: [],
				configform: {},
				option: {
					submitBtn: false,
					emptyBtn: false,
					column: [],
				},
			};
		},
		computed: {

		},
		created() {
			let param = this.$route.query;
			this.id = param.id;

			this.getDevice();
		},
		methods: {
			sendText() {
				client.publish(this.sendTheme, this.sendTextMessage);
			},
			getUserinfo() {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/user/userinfo',
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.userInfo = response.data.data;
							// mqtt连接

							that.mqttMSG();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},


			mqttMSG() {
				let that = this;
				console.log("准备连接MQTT,订阅主题", 'user/' + that.userInfo.id + "/" + that.device.code);
				console.log("连接状态：", that.userInfo);
				if (!this.clientStatus) {
					options.clientId = Math.floor(Math.random() * (9999999 - 1000000) + 1000000)
					client = mqtt.connect(MQTT_SERVICE, options)
				}
				client.on('connect', (e) => {
					this.clientStatus = true;
					console.log('连接成功:', that.device)
					//监听设备信息
					this.sendTheme = "all/" + that.device.code + "/sub",
						client.subscribe('user/' + that.userInfo.id + "/" + that.device.code, {
							qos: 1
						}, (error) => {
							if (!error) {
								console.log('订阅成功')
							} else {
								console.log('订阅失败')
							}
						})
					if (DEBUG) {
						//监听全部消息
						client.subscribe('all/' + that.device.code + "/#", {
							qos: 1
						}, (error) => {
							if (!error) {
								console.log('订阅成功')
							} else {
								console.log('订阅失败')
							}
						})
					}
				})
				// 接收消息处理
				client.on('message', (topic, message) => {

					var data = JSON.parse(message);
					let that = this;
					let deviceMessage = ["getAIStatusRsp", "postSysInfo", "reqSysInfoRsp", "cfgSysParamsRsp",
						"keepAlive", "cfgDOParamsRsp", "reqDOParamsRsp",
						"setDOStatusRsp", "getDOstatusRsp", "cfgDIParamsRsp", "reqDIParamsRsp",
						"getDIstatusRsp", "postDIInfo", "cfgAIParamsRsp", "reqAIParamsRsp",
						"getAIstatusRsp", "cfgPWMParamsRsp", "reqPWMParamsRsp", "setPWMStatusRsp",
						"getPWMstatusRsp", "cfgUARTParamsRsp", "reqUARTParamsRsp", "revUARTData"
					];
					let userMessage = ["reqSysInfo", "cfgSysParams", "getSysParams", "getSysParamsRsp",
						"cfgDOParams", "reqDOParams", "setDOStatus", "getDOStatus", "cfgDIParams",
						"reqDIParams", "getDIStatus", "cfgAIParams", "reqAIParams", "getAIStatus",
						"cfgPWMParams", "reqPWMParams", "setPWMStatus", "getPWMStatus", "cfgUARTParams",
						"reqUARTParams", "sendUARTData", "reboot", "reload"
					]
					let reqList = ['cfgDOParamsRsp', 'cfgDIParamsRsp', 'cfgAIParamsRsp', 'cfgPWMParamsRsp',
						'cfgUARTParamsRsp'
					];
					if (data.method === "cfgDOParamsRsp") {
						data.params.forEach(function(item, index) {
							that.DOData.forEach(function(detail, detailIndex) {
								console.log(item.num);
								if (item.num == detail.num) {
									detail.mode = item.mode + "";
									detail.isPost = item.isPost + "";
									detail.pulseTime = item.pulseTime;
								}
							})
						})
					} else if (data.method === "cfgDIParamsRsp") {
						data.params.forEach(function(item, index) {
							that.DIData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.isPost = item.isPost + "";
									///item.isPost===1?"Open":"Close";
								}
							})
						})
					} else if (data.method === "cfgAIParamsRsp") {
						data.params.forEach(function(item, index) {
							that.AIData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.isPost = item.isPost + "";
								}
							})
						})
					} else if (data.method === "cfgPWMParamsRsp") {
						data.params.forEach(function(item, index) {
							that.PWMData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.frqDiv = item.frqDiv;
									detail.highLevelCnt = item.highLevelCnt;
									detail.totalCnt = item.totalCnt;
								}
							})
						})
					} else if (data.method === "cfgUARTParamsRsp") {
						data.params.forEach(function(item, index) {
							that.UARTData.forEach(function(detail, detailIndex) {
								if (item.num == detail.num) {
									detail.baud = item.baud;
									detail.parity = item.parity;
									detail.stop = item.stop;
									detail.dataBits = item.dataBits;
								}
							})
						})
					}

					if (deviceMessage.indexOf(data.method) !== -1) {
						this.logText = this.logText + "↑  消息主题    " + topic + "\r\n";
						this.logText = this.logText + "   消息内容    " + JSON.stringify(data) + "\r\n\r\n";
					} else if (userMessage.indexOf(data.method) !== -1) {
						console.log("监听到用户消息");
						this.logText = this.logText + "↓  消息主题    " + topic + "\r\n";
						this.logText = this.logText + "   消息内容    " + JSON.stringify(data) + "\r\n\r\n";
					}


					if (that.isLoadding === true && that.loading !== null && reqList.indexOf(data.type) !== -1) {
						that.isLoadding = false;
						that.loading.close();
					}
				})
				// 断开发起重连
				client.on('reconnect', (error) => {
					console.log('正在重连:', error)
				})
				// 链接异常处理
				client.on('error', (error) => {
					console.log('连接失败:', error)
				})
			},

			getDevice() {
				let that = this;
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/getDevice',
						data: {
							id: that.id
						}
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.device = response.data.data;
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/getDeviceDetail',
						data: {
							id: that.id
						}
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							//DI显示
							response.data.data.DI.forEach(function(item, index) {
								that.DIData.push(item);
							})
							response.data.data.DO.forEach(function(item, index) {
								that.DOData.push(item);
							})
							response.data.data.AI.forEach(function(item, index) {
								that.AIData.push(item);
							})
							response.data.data.PWM.forEach(function(item, index) {
								that.PWMData.push(item);
							})
							response.data.data.UART.forEach(function(item, index) {
								that.UARTData.push(item);
							})
							that.getUserinfo();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},

			//DI更新
			DIUpdate(form, index, done, loading) {
				let that = this;
				done();
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/DIUpdate',
						data: form
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							console.log(form);
							that.isLoadding = true;
							that.DIData[index].name = form.name;
							that.loadding();
							/* that.$message.success(response.data.info);
							
							that.DIData[index].isPost = form.isPost; */
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},

			//AI更新
			AIUpdate(form, index, done, loading) {
				let that = this;
				done();
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/AIUpdate',
						data: form
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.isLoadding = true;
							that.AIData[index].name = form.name;
							that.loadding();
							/* that.$message.success(response.data.info);
							
							that.AIData[index].isPost = form.isPost;*/
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},

			//DO更新
			DOUpdate(form, index, done, loading) {
				let that = this;
				done();
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/DOUpdate',
						data: form
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.DOData[index].name = form.name;
							that.isLoadding = true;
							that.loadding();
							/* that.$message.success(response.data.info);

							
							that.DOData[index].mode = form.mode;
							that.DOData[index].pulseTime = form.pulseTime;
							that.DOData[index].isPost = form.isPost; */
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			PWMUpdate(form, index, done, loading) {
				let that = this;
				done();
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/PWMUpdate',
						data: form
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.isLoadding = true;
							that.PWMData[index].name = form.name;
							that.loadding();
							/* that.$message.success(response.data.info);
							
							that.PWMData[index].highLevelCnt = form.highLevelCnt;
							that.PWMData[index].frqDiv = form.frqDiv;
							that.PWMData[index].totalCnt = form.totalCnt; */
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			UARTUpdate(form, index, done, loading) {
				let that = this;
				done();
				request({
						headers: {
							'Content-Type': 'application/json;charset=utf-8'
						},
						method: 'post',
						url: baseUrl + '/api/device/UARTUpdate',
						data: form
					})
					.then(function(response) {
						if (response.data.status == 0) {
							that.$message.error(response.data.info)
						} else if (response.data.status == 1) {
							that.isLoadding = true;
							that.UARTData[index].name = form.name;
							that.loadding();
						}
					})
					.catch(function(error) {
						console.log(error);
						that.$message.error('系统错误')
					});
			},
			loadding() {
				this.loading = this.$loading({
					lock: true,
					text: this.$t("wel.table.loadding"),
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				setTimeout(() => {
					if (this.isLoadding) {
						this.loading.close();
						this.$message.error(this.$t("wel.table.timeOut"));
					}
				}, 10000);
			}
		},

	};
</script>

<style scoped="scoped" lang="scss">
	.wel {
		&__header {
			padding: 25px 40px;
			border-bottom: 1px solid #e8e8e8;
			background-color: #fff;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		&__info {
			display: flex;
			align-items: center;

			&-img {
				border-radius: 72px;
				display: block;
				width: 72px;
				height: 72px;

				img {
					width: 100%;
					height: 100%;
					display: block;
				}
			}

			&-content {
				position: relative;
				margin-left: 24px;
				color: rgba(0, 0, 0, 0.45);
				line-height: 22px;
			}

			&-title {
				font-size: 20px;
				line-height: 28px;
				font-weight: 500;
				color: rgba(0, 0, 0, 0.85);
				margin-bottom: 12px;
			}

			&-subtitle {
				position: relative;
				font-size: 14px;
				color: rgba(0, 0, 0, 0.45);
				line-height: 22px;
			}
		}

		&__extra {
			&-item {
				position: relative;
				padding: 0 32px;
				display: inline-block;

				&:last-child {
					&::after {
						display: none;
					}
				}

				&:after {
					background-color: #e8e8e8;
					position: absolute;
					top: 30px;
					right: 0;
					width: 1px;
					height: 40px;
					content: "";
				}
			}

			&-title {
				color: rgba(0, 0, 0, 0.45);
				font-size: 14px;
				line-height: 22px;
				margin-bottom: 4px;
			}

			&-subtitle {
				color: rgba(0, 0, 0, 0.85);
				font-size: 30px;
				line-height: 38px;
				margin: 0;

				span {
					color: rgba(0, 0, 0, 0.45);
					font-size: 20px;
				}
			}
		}
	}
</style>
